from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework.decorators import action
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet

from question.models import Label, Question, Reply
from question.serializers import LabelSerializer, QuestionSerializerCreat, \
    QuestionSerializerForList, ReplySerializerForCreate, LabelSerializerWithQuestionAndArticle, \
    QuestionSerializerForDetail, LabelFullSerializer


class LablesView(ListAPIView):
    """获取所有标签列表"""
    serializer_class = LabelSerializer
    queryset = Label.objects.all()
    pagination_class = None


class LablesUsersView(APIView):
    """用户关注的标签"""

    def get(self, request):
        try:
            user = request.user
        except Exception:
            user = None
        if user is not None and user.is_authenticated:
            queryset = user.labels.all()
            serializer = LabelSerializer(queryset, many=True)
            return Response(serializer.data)
        else:
            return Response([])


class LabelFocusin(APIView):
    """关注标签"""

    def put(self, request, id):
        try:
            user = self.request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated:
            label = Label.objects.get(pk=id)
            if user not in label.users.all():
                label.users.add(user)
                label.save()
                return Response({'success': True, 'message': '关注成功'})
            else:
                return Response({'success': True, 'message': '已经关注了...'})
        else:
            return Response({'success': False, 'message': '未登录'}, status=400)


class LabelFocusout(APIView):
    """取消关注标签"""

    def put(self, request, id):
        try:
            user = self.request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated:
            label = Label.objects.get(pk=id)
            if user in label.users.all():
                label.users.remove(user)
                label.save()
                return Response({'success': True, 'message': '关注成功'})
            else:
                return Response({'success': True, 'message': '还没有关注...'})
        else:
            return Response({'success': False, 'message': '未登录'}, status=400)


class LabelDetails(APIView):
    """获取标签详情"""

    def get(self, request, id):
        label = Label.objects.get(pk=id)
        serializer = LabelSerializerWithQuestionAndArticle(label)
        return Response(serializer.data)


class QuestionViewSet(ModelViewSet):
    queryset = Question.objects.all()

    def create(self, request, *args, **kwargs):
        """发布问题"""
        try:
            user = request.user
        except Exception:
            user = None
        if user is not None and user.is_authenticated:
            request_data = request.data
            request_data['user'] = user.id
            serializer = QuestionSerializerCreat(data=request_data)
            serializer.is_valid(raise_exception=True)
            serializer.save()
            return Response({'success': True, 'message': '发表成功'})
        else:
            return Response({'success': False, 'message': '未登录'}, status=400)

    def retrieve(self, request, pk):
        """问题详情"""
        question = self.get_object()
        question.visits += 1
        question.save()
        replies = question.replies.all()
        question.comment_question = []
        question.answer_question = []
        for item in replies:
            if item.type == 0:  # 问题的评论
                question.comment_question.append(item)
            elif item.type == 2:  # 回答的评论
                question.answer_question.append(item)
        serializer = QuestionSerializerForDetail(question)

        return Response(serializer.data)

    @action(methods=['put'], detail=True)
    def useful(self, request, pk):
        """问题有用"""
        try:
            user = request.user
        except Exception:
            user = None
        if user is not None and user.is_authenticated:
            redis_conn = get_redis_connection('question')
            flag = redis_conn.hget("question_userful_%s" % user.id, pk)
            if flag:
                return Response({'success': False, 'message': '请不要重复操作'})
            else:
                question = Question.objects.get(pk=pk)
                question.useful_count += 1
                question.save()
                redis_conn.hset("question_userful_%s" % user.id, pk, 1)
                return Response({'success': True, 'message': '更新成功'})
        else:
            return Response({'success': False, 'message': '未登录'}, status=400)

    @action(methods=['put'], detail=True)
    def unuseful(self, request, pk):
        """问题无用"""
        try:
            user = request.user
        except Exception:
            user = None
        if user is not None and user.is_authenticated:
            redis_conn = get_redis_connection('question')
            flag = redis_conn.hget("question_userful_%s" % user.id, pk)
            if flag:
                return Response({'success': False, 'message': '请不要重复操作'})
            else:
                question = Question.objects.get(pk=pk)
                question.unuseful_count += 1
                question.save()
                redis_conn.hset("question_userful_%s" % user.id, pk, 1)
                return Response({'success': True, 'message': '更新成功'})
        else:
            return Response({'success': False, 'message': '未登录'}, status=400)

    @action(methods=['get'], detail=True, url_path='label/new')
    def get_new_question_by_labelid(self, request, pk):
        """最新回答的问题"""
        if pk == '-1':
            questions = Question.objects.all().order_by('-replytime', '-id')
        else:
            label = Label.objects.get(id=pk)
            questions = label.questions.all().order_by('-replytime')
        serializer = QuestionSerializerForList(questions, many=True)

        return Response(serializer.data)

    @action(methods=['get'], detail=True, url_path='label/hot')
    def get_hot_question_by_labelid(self, request, pk):
        """热门回答的问题"""
        if pk == '-1':
            questions = Question.objects.all().order_by('-reply')
        else:
            label = Label.objects.get(id=pk)
            questions = label.questions.all().order_by('-reply')
        serializer = QuestionSerializerForList(questions, many=True)

        return Response(serializer.data)

    @action(methods=['get'], detail=True, url_path='label/wait')
    def get_wait_question_by_labelid(self, request, pk):
        """等待回答的问题"""
        if pk == '-1':
            questions = self.get_queryset().order_by('-createtime')
        else:
            label = Label.objects.get(id=pk)
            questions = label.questions.all()
        questions = questions.filter(reply=0).order_by('-createtime')
        serializer = QuestionSerializerForList(questions, many=True)

        return Response(serializer.data)


class ReplyViewSet(ModelViewSet):
    queryset = Reply.objects.all()

    def create(self, request, *args, **kwargs):
        """回答问题"""
        try:
            user = request.user
        except Exception:
            user = None
        if user is not None and user.is_authenticated:
            request_data = request.data
            request_data['user'] = user.id
            serializer = ReplySerializerForCreate(data=request_data)
            serializer.is_valid(raise_exception=True)
            reply = serializer.save()
            problem = reply.problem
            # 如果是回答, 则更新对应的数据
            if request_data.get('type') == 2:
                problem.reply += 1
                problem.replyname = reply.user.username
                problem.replytime = reply.createtime
                problem.save()
            return Response({'success': True, 'message': '发表成功'})
        else:
            return Response({'success': False, 'message': '未登录'}, status=400)

    @action(methods=['put'], detail=True)
    def useful(self, request, pk):
        """回答有用"""
        try:
            user = request.user
        except Exception:
            user = None
        if user is not None and user.is_authenticated:
            redis_conn = get_redis_connection('reply')
            flag = redis_conn.hget('reply_userful_%s' % user.id, pk)
            if flag:
                return Response({'success': False, 'message': '请不要重复操作'})
            else:
                replyitem = self.get_object()
                replyitem.useful_count += 1
                replyitem.save()
                replyitem.problem.solve = True
                replyitem.problem.save()
                redis_conn.hset('reply_userful_%s' % user.id, pk, 1)
                return Response({'success': True, 'message': '更新成功'})
        else:
            return Response({'success': False, 'message': '未登录'}, status=400)

    @action(methods=['put'], detail=True)
    def unuseful(self, request, pk):
        """回答没有"""
        try:
            user = request.user
        except Exception:
            user = None
        if user is not None and user.is_authenticated:
            redis_conn = get_redis_connection('reply')
            flag = redis_conn.hget("reply_userful_%s" % user.id, pk)
            if flag:
                return Response({'success': False, 'message': '请不要重复操作'})
            else:
                replyitem = self.get_object()
                replyitem.unuseful_count += 1
                replyitem.save()
                redis_conn.hset("reply_userful_%s" % user.id, pk, 1)
                return Response({'success': True, 'message': '更新成功'})
        else:
            return Response({'success': False, 'message': '未登录'}, status=400)


class LabelFull(APIView):
    """获取标签信息详情列表"""

    def get(self, request):
        labels = Label.objects.all()
        serializer = LabelFullSerializer(labels, many=True)
        return Response(serializer.data)